import {Button, Input, ScrollView, Text, View} from '@tarojs/components'
import Taro, {useDidShow} from '@tarojs/taro'
import type React from 'react'
import {useCallback, useState} from 'react'
import {type Contact, createContact, deleteContact, getContacts, setDefaultContact, updateContact} from '@/api'
import {isLoggedIn} from '@/utils/auth'

const Contacts: React.FC = () => {
  const [contacts, setContacts] = useState<Contact[]>([])
  const [loading, setLoading] = useState(true)
  const [showAddDialog, setShowAddDialog] = useState(false)
  const [editingContact, setEditingContact] = useState<Contact | null>(null)
  const [formData, setFormData] = useState({
    name: '',
    phone: '',
    id_card: '',
    is_default: false
  })

  // 加载联系人列表
  const loadContacts = useCallback(async () => {
    if (!isLoggedIn()) {
      Taro.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        Taro.navigateTo({url: '/pages/login/index'})
      }, 1500)
      return
    }

    setLoading(true)
    try {
      const result = await getContacts()
      if (result.success && result.data) {
        setContacts(Array.isArray(result.data) ? result.data : [])
      }
    } catch (error) {
      console.error('加载联系人失败:', error)
      Taro.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      setLoading(false)
    }
  }, [])

  useDidShow(() => {
    loadContacts()
  })

  // 打开添加对话框
  const handleAdd = () => {
    setEditingContact(null)
    setFormData({
      name: '',
      phone: '',
      id_card: '',
      is_default: false
    })
    setShowAddDialog(true)
  }

  // 打开编辑对话框
  const handleEdit = (contact: Contact) => {
    setEditingContact(contact)
    setFormData({
      name: contact.name,
      phone: contact.phone,
      id_card: contact.id_card,
      is_default: contact.is_default
    })
    setShowAddDialog(true)
  }

  // 保存联系人
  const handleSave = async () => {
    if (!formData.name.trim()) {
      Taro.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }

    if (!formData.phone.trim()) {
      Taro.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return
    }

    if (!/^1[3-9]\d{9}$/.test(formData.phone)) {
      Taro.showToast({
        title: '手机号格式不正确',
        icon: 'none'
      })
      return
    }

    if (!formData.id_card.trim()) {
      Taro.showToast({
        title: '请输入身份证号',
        icon: 'none'
      })
      return
    }

    if (!/^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/.test(formData.id_card)) {
      Taro.showToast({
        title: '身份证号格式不正确',
        icon: 'none'
      })
      return
    }

    try {
      if (editingContact) {
        // 更新联系人
        const result = await updateContact(editingContact.id, formData)
        if (result.success) {
          Taro.showToast({
            title: '更新成功',
            icon: 'success'
          })
          setShowAddDialog(false)
          loadContacts()
        }
      } else {
        // 创建联系人
        const result = await createContact(formData)
        if (result.success) {
          Taro.showToast({
            title: '添加成功',
            icon: 'success'
          })
          setShowAddDialog(false)
          loadContacts()
        }
      }
    } catch (error) {
      console.error('保存联系人失败:', error)
      Taro.showToast({
        title: '保存失败',
        icon: 'none'
      })
    }
  }

  // 删除联系人
  const handleDelete = async (contact: Contact) => {
    const res = await Taro.showModal({
      title: '确认删除',
      content: `确定要删除联系人"${contact.name}"吗？`
    })

    if (res.confirm) {
      try {
        const result = await deleteContact(contact.id)
        if (result.success) {
          Taro.showToast({
            title: '删除成功',
            icon: 'success'
          })
          loadContacts()
        }
      } catch (error) {
        console.error('删除联系人失败:', error)
        Taro.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    }
  }

  // 设置默认联系人
  const handleSetDefault = async (contact: Contact) => {
    try {
      const result = await setDefaultContact(contact.id)
      if (result.success) {
        Taro.showToast({
          title: '设置成功',
          icon: 'success'
        })
        loadContacts()
      }
    } catch (error) {
      console.error('设置默认联系人失败:', error)
      Taro.showToast({
        title: '设置失败',
        icon: 'none'
      })
    }
  }

  if (loading) {
    return (
      <View className="min-h-screen bg-gradient-to-b from-blue-50 to-white flex items-center justify-center">
        <Text className="text-gray-500">加载中...</Text>
      </View>
    )
  }

  return (
    <View className="min-h-screen" style={{background: 'linear-gradient(to bottom, #eff6ff, #ffffff)'}}>
      <ScrollView scrollY className="h-screen" style={{background: 'transparent'}}>
        <View className="p-4 pb-24">
          {/* 标题 */}
          <View className="mb-6">
            <Text className="text-2xl font-bold text-gray-900 block">常用联系人</Text>
            <Text className="text-sm text-gray-500 mt-1 block">管理您的常用联系人信息</Text>
          </View>

          {/* 添加按钮 */}
          <View className="mb-4">
            <Button
              className="w-full bg-blue-600 text-white py-3 rounded-lg font-bold text-base mt-6"
              style={{backgroundColor: '#2563eb', color: '#ffffff'}}
              onClick={handleAdd}>
              <View className="flex items-center justify-center gap-2">
                <View className="i-mdi-plus text-xl"></View>
                <Text className="text-white">添加联系人</Text>
              </View>
            </Button>
          </View>

          {/* 联系人列表 */}
          {contacts.length === 0 ? (
            <View className="bg-white rounded-2xl shadow-sm p-8 text-center">
              <View className="i-mdi-account-multiple-outline text-6xl text-gray-300 mb-4"></View>
              <Text className="text-gray-500 block">暂无联系人</Text>
              <Text className="text-sm text-gray-400 mt-2 block">点击上方按钮添加常用联系人</Text>
            </View>
          ) : (
            <View className="space-y-3">
              {contacts.map((contact) => (
                <View key={contact.id} className="bg-white rounded-2xl shadow-sm p-4">
                  <View className="flex items-start justify-between mb-3">
                    <View className="flex-1">
                      <View className="flex items-center gap-2 mb-1">
                        <Text className="text-lg font-bold text-gray-900">{contact.name}</Text>
                        {contact.is_default && (
                          <View className="px-2 py-0.5 bg-blue-100 rounded">
                            <Text className="text-xs text-blue-600 font-medium">默认</Text>
                          </View>
                        )}
                      </View>
                      <Text className="text-sm text-gray-600 block">手机号：{contact.phone}</Text>
                      <Text className="text-sm text-gray-600 block mt-1">
                        身份证：{contact.id_card.replace(/^(.{6})(?:\d+)(.{4})$/, '$1********$2')}
                      </Text>
                    </View>
                  </View>

                  <View className="flex gap-2 pt-3 border-t border-gray-100">
                    {!contact.is_default && (
                      <Button
                        size="mini"
                        className="flex-1 py-2 bg-blue-50 text-blue-600 text-sm"
                        style={{backgroundColor: '#eff6ff', color: '#2563eb', border: 'none'}}
                        onClick={() => handleSetDefault(contact)}>
                        设为默认
                      </Button>
                    )}
                    <Button
                      size="mini"
                      className="flex-1 bg-gray-50 text-gray-700 text-sm"
                      style={{backgroundColor: '#f9fafb', color: '#374151', border: 'none'}}
                      onClick={() => handleEdit(contact)}>
                      编辑
                    </Button>
                    <Button
                      size="mini"
                      className="flex-1 bg-red-50 text-red-600  text-sm"
                      style={{backgroundColor: '#fef2f2', color: '#dc2626', border: 'none'}}
                      onClick={() => handleDelete(contact)}>
                      删除
                    </Button>
                  </View>
                </View>
              ))}
            </View>
          )}
        </View>
      </ScrollView>

      {/* 添加/编辑对话框 */}
      {showAddDialog && (
        <View
          className="fixed inset-0 flex items-center justify-center z-50"
          style={{backgroundColor: 'rgba(0,0,0,0.5)'}}>
          <View className="bg-white rounded-2xl p-6 mx-4 w-full max-w-md">
            <Text className="text-xl font-bold text-gray-900 mb-4 block">
              {editingContact ? '编辑联系人' : '添加联系人'}
            </Text>

            <View className="space-y-4">
              <View>
                <Text className="text-sm text-gray-700 mb-2 block">姓名</Text>
                <Input
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                  placeholder="请输入姓名"
                  value={formData.name}
                  onInput={(e) => setFormData({...formData, name: e.detail.value})}
                />
              </View>

              <View>
                <Text className="text-sm text-gray-700 mb-2 block">手机号</Text>
                <Input
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                  placeholder="请输入手机号"
                  type="number"
                  maxlength={11}
                  value={formData.phone}
                  onInput={(e) => setFormData({...formData, phone: e.detail.value})}
                />
              </View>

              <View>
                <Text className="text-sm text-gray-700 mb-2 block">身份证号</Text>
                <Input
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg text-sm"
                  placeholder="请输入身份证号"
                  maxlength={18}
                  value={formData.id_card}
                  onInput={(e) => setFormData({...formData, id_card: e.detail.value.toUpperCase()})}
                />
              </View>

              <View className="flex items-center gap-2 pt-2">
                <View
                  className="w-5 h-5 rounded border-2 flex items-center justify-center"
                  style={{
                    borderColor: formData.is_default ? '#2563eb' : '#d1d5db',
                    backgroundColor: formData.is_default ? '#2563eb' : 'transparent'
                  }}
                  onClick={() => setFormData({...formData, is_default: !formData.is_default})}>
                  {formData.is_default && <View className="i-mdi-check text-white text-sm"></View>}
                </View>
                <Text className="text-sm text-gray-700">设为默认联系人</Text>
              </View>
            </View>

            <View className="flex gap-3 mt-6">
              <Button
                size="default"
                className="flex-1 bg-gray-100 text-gray-700 text-base mt-6 py-3 "
                style={{backgroundColor: '#f3f4f6', color: '#374151'}}
                onClick={() => setShowAddDialog(false)}>
                取消
              </Button>
              <Button
                size="default"
                className="flex-1 bg-blue-600 text-white text-base mt-6 py-3 "
                style={{backgroundColor: '#2563eb', color: '#ffffff'}}
                onClick={handleSave}>
                保存
              </Button>
            </View>
          </View>
        </View>
      )}
    </View>
  )
}

export default Contacts
